<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Spring源码系列-第2章-后置工厂处理器和Bean生命周期 | 风祈的时光录</title><meta name="keywords" content="Spring，框架，spring源码"><meta name="author" content="youthlql"><meta name="copyright" content="youthlql"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="开始讲最重要的xxxPostProcessor">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring源码系列-第2章-后置工厂处理器和Bean生命周期">
<meta property="og:url" content="https://imlql.cn/post/41fb8d9e.html">
<meta property="og:site_name" content="风祈的时光录">
<meta property="og:description" content="开始讲最重要的xxxPostProcessor">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png">
<meta property="article:published_time" content="2021-12-21T12:21:58.000Z">
<meta property="article:modified_time" content="2022-07-24T11:22:15.048Z">
<meta property="article:author" content="youthlql">
<meta property="article:tag" content="Spring源码">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png"><link rel="shortcut icon" href="https://npm.elemecdn.com/youthlql@1.0.8/blog/favicon.png"><link rel="canonical" href="https://imlql.cn/post/41fb8d9e"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f693ff99cc7e613b88cf5b729a14b48b";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring源码系列-第2章-后置工厂处理器和Bean生命周期',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-24 19:22:15'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/ali_icon.css"><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/2-24-mogai.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="风祈的时光录" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/avatar/2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">37</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://npm.elemecdn.com/lql_static@latest/logo/spring.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">风祈的时光录</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring源码系列-第2章-后置工厂处理器和Bean生命周期</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-12-21T12:21:58.000Z" title="发表于 2021-12-21 20:21:58">2021-12-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-24T11:22:15.048Z" title="更新于 2022-07-24 19:22:15">2022-07-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/">Spring</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/%E6%BA%90%E7%A0%81V1/">源码V1</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">5.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>26分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="第2章-后置工厂处理器和Bean生命周期"><a href="#第2章-后置工厂处理器和Bean生命周期" class="headerlink" title="第2章-后置工厂处理器和Bean生命周期"></a>第2章-后置工厂处理器和Bean生命周期</h1><blockquote>
<p>后置工厂处理器属于后置处理器，后置处理器是Spring最核心的部分，Spring几乎所有的附加功能全由它完成。</p>
</blockquote>
<h2 id="什么是BeanPostProcessor？"><a href="#什么是BeanPostProcessor？" class="headerlink" title="什么是BeanPostProcessor？"></a>什么是BeanPostProcessor？</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">BeanPostProcessor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Apply this &#123;<span class="doctag">@code</span> BeanPostProcessor&#125; to the given new bean instance &lt;i&gt;before&lt;/i&gt; any bean</span></span><br><span class="line"><span class="comment">    * initialization callbacks (like InitializingBean&#x27;s &#123;<span class="doctag">@code</span> afterPropertiesSet&#125;</span></span><br><span class="line"><span class="comment">    * or a custom init-method). The bean will already be populated with property values.</span></span><br><span class="line"><span class="comment">    * The returned bean instance may be a wrapper around the original.</span></span><br><span class="line"><span class="comment">    * &lt;p&gt;The default implementation returns the given &#123;<span class="doctag">@code</span> bean&#125; as-is.</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> bean the new bean instance</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> beanName the name of the bean</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@return</span> the bean instance to use, either the original or a wrapped one;</span></span><br><span class="line"><span class="comment">    * if &#123;<span class="doctag">@code</span> null&#125;, no subsequent BeanPostProcessors will be invoked</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@throws</span> org.springframework.beans.BeansException in case of errors</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@see</span> org.springframework.beans.factory.InitializingBean#afterPropertiesSet</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="meta">@Nullable</span></span><br><span class="line">   <span class="function"><span class="keyword">default</span> Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> bean;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/*</span></span><br><span class="line"><span class="comment">   将这个&#123;@code BeanPostProcessor&#125;应用到给定的新bean实例&lt;i&gt;在&lt;i&gt;任何bean初始化回调之后</span></span><br><span class="line"><span class="comment">   (如InitializingBean的&#123;@code afterPropertiesSet&#125;</span></span><br><span class="line"><span class="comment">   或自定义初始化方法)。bean将已经被属性值填充。返回的bean实例可能是原始bean的包装器。</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Apply this &#123;<span class="doctag">@code</span> BeanPostProcessor&#125; to the given new bean instance &lt;i&gt;after&lt;/i&gt; any bean</span></span><br><span class="line"><span class="comment">    * initialization callbacks (like InitializingBean&#x27;s &#123;<span class="doctag">@code</span> afterPropertiesSet&#125;</span></span><br><span class="line"><span class="comment">    * or a custom init-method). The bean will already be populated with property values.</span></span><br><span class="line"><span class="comment">    * The returned bean instance may be a wrapper around the original.</span></span><br><span class="line"><span class="comment">    * &lt;p&gt;In case of a FactoryBean, this callback will be invoked for both the FactoryBean</span></span><br><span class="line"><span class="comment">    * instance and the objects created by the FactoryBean (as of Spring 2.0). The</span></span><br><span class="line"><span class="comment">    * post-processor can decide whether to apply to either the FactoryBean or created</span></span><br><span class="line"><span class="comment">    * objects or both through corresponding &#123;<span class="doctag">@code</span> bean instanceof FactoryBean&#125; checks.</span></span><br><span class="line"><span class="comment">    * &lt;p&gt;This callback will also be invoked after a short-circuiting triggered by a</span></span><br><span class="line"><span class="comment">    * &#123;<span class="doctag">@link</span> InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation&#125; method,</span></span><br><span class="line"><span class="comment">    * in contrast to all other &#123;<span class="doctag">@code</span> BeanPostProcessor&#125; callbacks.</span></span><br><span class="line"><span class="comment">    * &lt;p&gt;The default implementation returns the given &#123;<span class="doctag">@code</span> bean&#125; as-is.</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> bean the new bean instance</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> beanName the name of the bean</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@return</span> the bean instance to use, either the original or a wrapped one;</span></span><br><span class="line"><span class="comment">    * if &#123;<span class="doctag">@code</span> null&#125;, no subsequent BeanPostProcessors will be invoked</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@throws</span> org.springframework.beans.BeansException in case of errors</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@see</span> org.springframework.beans.factory.InitializingBean#afterPropertiesSet</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@see</span> org.springframework.beans.factory.FactoryBean</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="meta">@Nullable</span></span><br><span class="line">   <span class="function"><span class="keyword">default</span> Object <span class="title">postProcessAfterInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> bean;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个是要干什么呢？BeanPostProcessor类中的注释本身没有说的太明白，我们可以来看下另一个后置处理器</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@FunctionalInterface</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">BeanFactoryPostProcessor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Modify the application context&#x27;s internal bean factory after its standard</span></span><br><span class="line"><span class="comment">    * initialization. All bean definitions will have been loaded, but no beans</span></span><br><span class="line"><span class="comment">    * will have been instantiated yet. This allows for overriding or adding</span></span><br><span class="line"><span class="comment">    * properties even to eager-initializing beans.</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> beanFactory the bean factory used by the application context</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@throws</span> org.springframework.beans.BeansException in case of errors</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="function"><span class="keyword">void</span> <span class="title">postProcessBeanFactory</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928171641029.png"/>

<p>核心就是我们对于传进来的参数，可以<strong>修改，覆盖，添加</strong>它的东西。对于BeanPostProcessor来说，传进来的参数是<code>(Object bean, String beanName)</code> ，它都已经把bean传给你了，这意味着我们可以修改传进来的Bean的任何东西。不管你是事务也好，AOP也好，都是通过这些个后置处理器来添加这些额外功能的。</p>
<p>BeanPostProcessor：后置增强普通的Bean组件<br>BeanFactoryPostProcessor：后置增强BeanFactory，也就是增强Bean工厂</p>
<h3 id="BeanFactoryPostProcessor的接口关系"><a href="#BeanFactoryPostProcessor的接口关系" class="headerlink" title="BeanFactoryPostProcessor的接口关系"></a>BeanFactoryPostProcessor的接口关系</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928172716846.png" />

<h3 id="BeanPostProcessor接口关系"><a href="#BeanPostProcessor接口关系" class="headerlink" title="BeanPostProcessor接口关系"></a>BeanPostProcessor接口关系</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928173012384.png"/>

<p>DestructionAwareBeanPostProcessor接口是跟销毁有关的，我们这里不分析</p>
<blockquote>
<p>之前说过，分析源码时，优先看接口继承关系，好的框架大部分都是遵循<strong>基于接口而非实现</strong>这一设计思想。</p>
</blockquote>
<h2 id="什么是InitializingBean？"><a href="#什么是InitializingBean？" class="headerlink" title="什么是InitializingBean？"></a>什么是InitializingBean？</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">InitializingBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//翻译： 该方法允许bean实例在设置了所有bean属性后对其总体配置和最终初始化执行验证</span></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * Invoked by the containing &#123;<span class="doctag">@code</span> BeanFactory&#125; after it has set all bean properties</span></span><br><span class="line"><span class="comment">	 * and satisfied &#123;<span class="doctag">@link</span> BeanFactoryAware&#125;, &#123;<span class="doctag">@code</span> ApplicationContextAware&#125; etc.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;This method allows the bean instance to perform validation of its overall</span></span><br><span class="line"><span class="comment">	 * configuration and final initialization when all bean properties have been set.</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@throws</span> Exception in the event of misconfiguration (such as failure to set an</span></span><br><span class="line"><span class="comment">	 * essential property) or if initialization fails for any other reason</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol>
<li>Bean组件初始化以后对组件进行后续设置，因为它没有参数传进来，它改变不了什么东西，它的目的在于额外处理。</li>
<li>后面我们会讲到BeanPostProcessor主要用于Spring中大部分组件都会用到的功能处理。而InitializingBean是单组件处理（做一些额外处理），最好的例子就是SpringMVC里的一些组件，后面讲。</li>
</ol>
<h2 id="测试类"><a href="#测试类" class="headerlink" title="测试类"></a>测试类</h2><h3 id="MyBeanPostProcessor"><a href="#MyBeanPostProcessor" class="headerlink" title="MyBeanPostProcessor"></a>MyBeanPostProcessor</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBeanPostProcessor</span> <span class="keyword">implements</span> <span class="title">BeanPostProcessor</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MyBeanPostProcessor</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanPostProcessor...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessAfterInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanPostProcessor...postProcessAfterInitialization...&quot;</span>+bean+<span class="string">&quot;==&gt;&quot;</span>+beanName);</span><br><span class="line">      <span class="keyword">return</span> bean;</span><br><span class="line">   &#125;</span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanPostProcessor...postProcessBeforeInitialization...&quot;</span>+bean+<span class="string">&quot;==&gt;&quot;</span>+beanName);</span><br><span class="line">      <span class="keyword">return</span> bean;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="MyInstantiationAwareBeanPostProcessor"><a href="#MyInstantiationAwareBeanPostProcessor" class="headerlink" title="MyInstantiationAwareBeanPostProcessor"></a>MyInstantiationAwareBeanPostProcessor</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyInstantiationAwareBeanPostProcessor</span> <span class="keyword">implements</span> <span class="title">InstantiationAwareBeanPostProcessor</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MyInstantiationAwareBeanPostProcessor</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyInstantiationAwareBeanPostProcessor...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInstantiation</span><span class="params">(Class&lt;?&gt; beanClass, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyInstantiationAwareBeanPostProcessor...postProcessBeforeInstantiation=&gt;&quot;</span>+beanClass+<span class="string">&quot;--&quot;</span>+beanName);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">postProcessAfterInstantiation</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyInstantiationAwareBeanPostProcessor...postProcessAfterInstantiation=&gt;&quot;</span>+bean+<span class="string">&quot;--&quot;</span>+beanName);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">   &#125;</span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> PropertyValues <span class="title">postProcessProperties</span><span class="params">(PropertyValues pvs, Object bean, String beanName)</span></span></span><br><span class="line"><span class="function">         <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyInstantiationAwareBeanPostProcessor...postProcessProperties=&gt;&quot;</span>+bean+<span class="string">&quot;--&quot;</span>+beanName);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="MyMergedBeanDefinitionPostProcessor"><a href="#MyMergedBeanDefinitionPostProcessor" class="headerlink" title="MyMergedBeanDefinitionPostProcessor"></a>MyMergedBeanDefinitionPostProcessor</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyMergedBeanDefinitionPostProcessor</span> <span class="keyword">implements</span> <span class="title">MergedBeanDefinitionPostProcessor</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MyMergedBeanDefinitionPostProcessor</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyMergedBeanDefinitionPostProcessor...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyMergedBeanDefinitionPostProcessor...postProcessBeforeInitialization...=&gt;&quot;</span>+bean+<span class="string">&quot;--&quot;</span>+beanName);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessAfterInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyMergedBeanDefinitionPostProcessor...postProcessAfterInitialization..=&gt;&quot;</span>+bean+<span class="string">&quot;--&quot;</span>+beanName);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessMergedBeanDefinition</span><span class="params">(RootBeanDefinition beanDefinition, Class&lt;?&gt; beanType, String beanName)</span> </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyMergedBeanDefinitionPostProcessor...postProcessMergedBeanDefinition..=&gt;&quot;</span>+beanName+<span class="string">&quot;--&quot;</span>+beanType+<span class="string">&quot;---&quot;</span>+beanDefinition);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">resetBeanDefinition</span><span class="params">(String beanName)</span> </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyMergedBeanDefinitionPostProcessor...resetBeanDefinition..&quot;</span>+beanName);</span><br><span class="line"></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="MySmartInstantiationAwareBeanPostProcessor"><a href="#MySmartInstantiationAwareBeanPostProcessor" class="headerlink" title="MySmartInstantiationAwareBeanPostProcessor"></a>MySmartInstantiationAwareBeanPostProcessor</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MySmartInstantiationAwareBeanPostProcessor</span> <span class="keyword">implements</span> <span class="title">SmartInstantiationAwareBeanPostProcessor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MySmartInstantiationAwareBeanPostProcessor</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MySmartInstantiationAwareBeanPostProcessor...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">    </span><br><span class="line">   <span class="keyword">public</span> Class&lt;?&gt; predictBeanType(Class&lt;?&gt; beanClass, String beanName) <span class="keyword">throws</span> BeansException &#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MySmartInstantiationAwareBeanPostProcessor...predictBeanType=&gt;&quot;</span>+beanClass+<span class="string">&quot;--&quot;</span>+beanName);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">public</span> Constructor&lt;?&gt;[] determineCandidateConstructors(Class&lt;?&gt; beanClass, String beanName)</span><br><span class="line"></span><br><span class="line">         <span class="keyword">throws</span> BeansException &#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MySmartInstantiationAwareBeanPostProcessor...determineCandidateConstructors=&gt;&quot;</span>+beanClass+<span class="string">&quot;--&quot;</span>+beanName);</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">getEarlyBeanReference</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MySmartInstantiationAwareBeanPostProcessor...getEarlyBeanReference=&gt;&quot;</span>+bean+<span class="string">&quot;--&quot;</span>+beanName);</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> bean;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="MyInitializingBean"><a href="#MyInitializingBean" class="headerlink" title="MyInitializingBean"></a>MyInitializingBean</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 生命周期接口</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyInitializingBean</span> <span class="keyword">implements</span> <span class="title">InitializingBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MyInitializingBean</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyInitializingBean....&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyInitializingBean...afterPropertiesSet...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="MyBeanFactoryPostProcessor"><a href="#MyBeanFactoryPostProcessor" class="headerlink" title="MyBeanFactoryPostProcessor"></a>MyBeanFactoryPostProcessor</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * BeanFactory的后置处理器</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBeanFactoryPostProcessor</span> <span class="keyword">implements</span> <span class="title">BeanFactoryPostProcessor</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MyBeanFactoryPostProcessor</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanFactoryPostProcessor...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">    </span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessBeanFactory</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;BeanFactoryPostProcessor....postProcessBeanFactory==&gt;&quot;</span>+beanFactory);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="MyBeanDefinitionRegistryPostProcessor"><a href="#MyBeanDefinitionRegistryPostProcessor" class="headerlink" title="MyBeanDefinitionRegistryPostProcessor"></a>MyBeanDefinitionRegistryPostProcessor</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBeanDefinitionRegistryPostProcessor</span> <span class="keyword">implements</span> <span class="title">BeanDefinitionRegistryPostProcessor</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MyBeanDefinitionRegistryPostProcessor</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanDefinitionRegistryPostProcessor&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">    </span><br><span class="line">   <span class="meta">@Override</span>  <span class="comment">//紧接着执行</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessBeanFactory</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanDefinitionRegistryPostProcessor....postProcessBeanFactory...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span>  <span class="comment">//先执行的</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessBeanDefinitionRegistry</span><span class="params">(BeanDefinitionRegistry registry)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MyBeanDefinitionRegistryPostProcessor...postProcessBeanDefinitionRegistry...&quot;</span>);</span><br><span class="line">      <span class="comment">//增强bean定义信息的注册中心，比如自己注册组件</span></span><br><span class="line"></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Cat"><a href="#Cat" class="headerlink" title="Cat"></a>Cat</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cat</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">Cat</span><span class="params">()</span></span>&#123;</span><br><span class="line">		System.out.println(<span class="string">&quot;cat被创建了...&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="meta">@Value(&quot;$&#123;JAVA_HOME&#125;&quot;)</span> <span class="comment">//自动赋值功能</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">		System.out.println(<span class="string">&quot;cat....setName正在赋值调用....&quot;</span>);</span><br><span class="line">		<span class="keyword">this</span>.name = name;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> name;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="beans2-xml"><a href="#beans2-xml" class="headerlink" title="beans2.xml"></a>beans2.xml</h3><figure class="highlight"><table><tr><td class="code"><pre><span class="line">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span><br><span class="line">&lt;beans xmlns=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span><br><span class="line">	   xmlns:xsi=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span><br><span class="line">	   xmlns:context=<span class="string">&quot;http://www.springframework.org/schema/context&quot;</span></span><br><span class="line">	   xsi:schemaLocation=<span class="string">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd&quot;</span>&gt;</span><br><span class="line"></span><br><span class="line">	&lt;context:component-scan base-<span class="keyword">package</span>=<span class="string">&quot;cn.imlql.spring.processor&quot;</span>/&gt;</span><br><span class="line"></span><br><span class="line">	&lt;bean <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;cn.imlql.spring.bean.Cat&quot;</span> id=<span class="string">&quot;cat&quot;</span>/&gt;</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure>

<h3 id="MainTest"><a href="#MainTest" class="headerlink" title="MainTest"></a>MainTest</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		ClassPathXmlApplicationContext context = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">&quot;beans2.xml&quot;</span>);</span><br><span class="line">		Person bean = context.getBean(Person.class);</span><br><span class="line">		System.out.println(bean);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>给上面的<strong>所有方法</strong>都打上断点，我们跟着调用栈一步一步看Bean的生命周期里，这些东西是什么时候参与进来的，哪个在前，哪个在后。</p>
<h2 id="后置工厂处理器如何参与的Bean生命周期"><a href="#后置工厂处理器如何参与的Bean生命周期" class="headerlink" title="后置工厂处理器如何参与的Bean生命周期"></a>后置工厂处理器如何参与的Bean生命周期</h2><blockquote>
<p>标题的先后顺序就是后置处理器进入的先后顺序</p>
</blockquote>
<h3 id="流程图-Bean生命周期与后置工厂处理器"><a href="#流程图-Bean生命周期与后置工厂处理器" class="headerlink" title="流程图-Bean生命周期与后置工厂处理器"></a>流程图-Bean生命周期与后置工厂处理器</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.7/spring-sourcecode-v1/flow_chart/Bean%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E4%B8%8E%E5%90%8E%E7%BD%AE%E5%B7%A5%E5%8E%82%E5%A4%84%E7%90%86%E5%99%A8.png">

<h3 id="BeanDefinitionRegistryPostProcessor"><a href="#BeanDefinitionRegistryPostProcessor" class="headerlink" title="BeanDefinitionRegistryPostProcessor"></a>BeanDefinitionRegistryPostProcessor</h3><h4 id="执行无参构造"><a href="#执行无参构造" class="headerlink" title="执行无参构造"></a>执行无参构造</h4><h5 id="Debug调用栈"><a href="#Debug调用栈" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h5><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928193241982.png"/>

<h5 id="AbstractApplicationContext-refresh"><a href="#AbstractApplicationContext-refresh" class="headerlink" title="AbstractApplicationContext#refresh()"></a>AbstractApplicationContext#refresh()</h5><blockquote>
<p>和以前一样，目前用不到的源码都省略，最后会逐渐给一个完整的源码注释。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Override</span>  <span class="comment">//容器刷新的十二大步。</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refresh</span><span class="params">()</span> <span class="keyword">throws</span> BeansException, IllegalStateException </span>&#123;</span><br><span class="line">      <span class="keyword">synchronized</span> (<span class="keyword">this</span>.startupShutdownMonitor) &#123;</span><br><span class="line">         StartupStep contextRefresh = <span class="keyword">this</span>.applicationStartup.start(<span class="string">&quot;spring.context.refresh&quot;</span>);</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Prepare this context for refreshing.</span></span><br><span class="line">         prepareRefresh();</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Tell the subclass to refresh the internal bean factory.</span></span><br><span class="line">         <span class="comment">// 工厂创建：BeanFactory第一次开始创建的时候,有xml解析逻辑。</span></span><br><span class="line">         ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Prepare the bean factory for use in this context.</span></span><br><span class="line">         prepareBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">         <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// Allows post-processing of the bean factory in context subclasses.</span></span><br><span class="line">            postProcessBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">            StartupStep beanPostProcess = <span class="keyword">this</span>.applicationStartup.start(<span class="string">&quot;spring.context.beans.post-process&quot;</span>);</span><br><span class="line">            <span class="comment">//工厂增强：执行所有的BeanFactory后置增强器；利用BeanFactory后置增强器对工厂进行修改或者增强,配置类会在这里进行解析。 </span></span><br><span class="line">            invokeBeanFactoryPostProcessors(beanFactory);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//注册所有的Bean的后置处理器 Register bean processors that intercept bean creation.</span></span><br><span class="line">            registerBeanPostProcessors(beanFactory);</span><br><span class="line">            beanPostProcess.end();</span><br><span class="line"></span><br><span class="line">           <span class="comment">//...</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// Instantiate all remaining (non-lazy-init) singletons.</span></span><br><span class="line">            <span class="comment">//bean创建；完成 BeanFactory 初始化。（工厂里面所有的组件都好了）</span></span><br><span class="line">            finishBeanFactoryInitialization(beanFactory);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Last step: publish corresponding event.</span></span><br><span class="line">            finishRefresh();</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">invokeBeanFactoryPostProcessors</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> </span>&#123;</span><br><span class="line">	PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); <span class="comment">//执行所有的工厂增强器</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime</span></span><br><span class="line">	<span class="comment">// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)</span></span><br><span class="line">	<span class="keyword">if</span> (!NativeDetector.inNativeImage() &amp;&amp; beanFactory.getTempClassLoader() == <span class="keyword">null</span> &amp;&amp; beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) &#123;</span><br><span class="line">		beanFactory.addBeanPostProcessor(<span class="keyword">new</span> LoadTimeWeaverAwareProcessor(beanFactory));</span><br><span class="line">		beanFactory.setTempClassLoader(<span class="keyword">new</span> ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="PostProcessorRegistrationDelegate-invokeBeanFactoryPostProcessors"><a href="#PostProcessorRegistrationDelegate-invokeBeanFactoryPostProcessors" class="headerlink" title="PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors()"></a>PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors()</h5><blockquote>
<p>此类没有省略代码</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">invokeBeanFactoryPostProcessors</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">      ConfigurableListableBeanFactory beanFactory, List&lt;BeanFactoryPostProcessor&gt; beanFactoryPostProcessors)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// WARNING: Although it may appear that the body of this method can be easily</span></span><br><span class="line">   <span class="comment">// refactored to avoid the use of multiple loops and multiple lists, the use</span></span><br><span class="line">   <span class="comment">// of multiple lists and multiple passes over the names of processors is</span></span><br><span class="line">   <span class="comment">// intentional. We must ensure that we honor the contracts for PriorityOrdered</span></span><br><span class="line">   <span class="comment">// and Ordered processors. Specifically, we must NOT cause processors to be</span></span><br><span class="line">   <span class="comment">// instantiated (via getBean() invocations) or registered in the ApplicationContext</span></span><br><span class="line">   <span class="comment">// in the wrong order.</span></span><br><span class="line">   <span class="comment">//</span></span><br><span class="line">   <span class="comment">// Before submitting a pull request (PR) to change this method, please review the</span></span><br><span class="line">   <span class="comment">// list of all declined PRs involving changes to PostProcessorRegistrationDelegate</span></span><br><span class="line">   <span class="comment">// to ensure that your proposal does not result in a breaking change:</span></span><br><span class="line">   <span class="comment">// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22</span></span><br><span class="line"></span><br><span class="line">   <span class="comment">// Invoke BeanDefinitionRegistryPostProcessors first, if any.</span></span><br><span class="line">   Set&lt;String&gt; processedBeans = <span class="keyword">new</span> HashSet&lt;&gt;();</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (beanFactory <span class="keyword">instanceof</span> BeanDefinitionRegistry) &#123;</span><br><span class="line">      BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;</span><br><span class="line">      List&lt;BeanFactoryPostProcessor&gt; regularPostProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">      List&lt;BeanDefinitionRegistryPostProcessor&gt; registryProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">      <span class="comment">//先拿到底层默认有的BeanFactoryPostProcessor</span></span><br><span class="line">      <span class="keyword">for</span> (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) &#123;</span><br><span class="line">         <span class="keyword">if</span> (postProcessor <span class="keyword">instanceof</span> BeanDefinitionRegistryPostProcessor) &#123;</span><br><span class="line">            BeanDefinitionRegistryPostProcessor registryProcessor =</span><br><span class="line">                  (BeanDefinitionRegistryPostProcessor) postProcessor;</span><br><span class="line">            registryProcessor.postProcessBeanDefinitionRegistry(registry);</span><br><span class="line">            registryProcessors.add(registryProcessor);</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">else</span> &#123;</span><br><span class="line">            regularPostProcessors.add(postProcessor);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Do not initialize FactoryBeans here: We need to leave all regular beans</span></span><br><span class="line">      <span class="comment">// uninitialized to let the bean factory post-processors apply to them!</span></span><br><span class="line">      <span class="comment">// Separate between BeanDefinitionRegistryPostProcessors that implement</span></span><br><span class="line">      <span class="comment">// PriorityOrdered, Ordered, and the rest.</span></span><br><span class="line">      List&lt;BeanDefinitionRegistryPostProcessor&gt; currentRegistryProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 首先：从工厂中获取所有的实现了 PriorityOrdered 接口的 BeanDefinitionRegistryPostProcessor； 之前xml解析的时候就已经注册了BeanDefinition</span></span><br><span class="line">      String[] postProcessorNames =</span><br><span class="line">            beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, <span class="keyword">true</span>, <span class="keyword">false</span>);</span><br><span class="line">      <span class="keyword">for</span> (String ppName : postProcessorNames) &#123;</span><br><span class="line">         <span class="keyword">if</span> (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) &#123;</span><br><span class="line">            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));<span class="comment">//从工厂中获取这个组件【getBean整个组件创建的流程】并放到这个集合</span></span><br><span class="line">            processedBeans.add(ppName);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125; <span class="comment">//下面利用优先级排序</span></span><br><span class="line">      sortPostProcessors(currentRegistryProcessors, beanFactory);</span><br><span class="line">      registryProcessors.addAll(currentRegistryProcessors);</span><br><span class="line">      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup()); <span class="comment">//执行这些BeanDefinitionRegistryPostProcessor的</span></span><br><span class="line">      currentRegistryProcessors.clear();</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 接下来，获取所有实现了Ordered接口的 BeanDefinitionRegistryPostProcessor Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.</span></span><br><span class="line">      postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, <span class="keyword">true</span>, <span class="keyword">false</span>);</span><br><span class="line">      <span class="keyword">for</span> (String ppName : postProcessorNames) &#123;</span><br><span class="line">         <span class="keyword">if</span> (!processedBeans.contains(ppName) &amp;&amp; beanFactory.isTypeMatch(ppName, Ordered.class)) &#123;</span><br><span class="line">            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));</span><br><span class="line">            processedBeans.add(ppName); <span class="comment">//即使同时实现了 PriorityOrdered 和Ordered，也是以 PriorityOrdered为准</span></span><br><span class="line">         &#125;</span><br><span class="line">      &#125;<span class="comment">//排序</span></span><br><span class="line">      sortPostProcessors(currentRegistryProcessors, beanFactory);</span><br><span class="line">      registryProcessors.addAll(currentRegistryProcessors);</span><br><span class="line">      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup()); <span class="comment">//执行</span></span><br><span class="line">      currentRegistryProcessors.clear();</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 最后，我们自定义的一般没有任何优先级和排序接口   Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.</span></span><br><span class="line">      <span class="keyword">boolean</span> reiterate = <span class="keyword">true</span>;</span><br><span class="line">      <span class="keyword">while</span> (reiterate) &#123;</span><br><span class="line">         reiterate = <span class="keyword">false</span>;</span><br><span class="line">         postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, <span class="keyword">true</span>, <span class="keyword">false</span>);<span class="comment">//拿到所有的BeanDefinitionRegistryPostProcessor</span></span><br><span class="line">         <span class="keyword">for</span> (String ppName : postProcessorNames) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!processedBeans.contains(ppName)) &#123;</span><br><span class="line">                <span class="comment">//然后这里就开始走前面讲过的getBean,无参构造创建对象的流程    =====&gt; 跳转到其它方法</span></span><br><span class="line">               currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));</span><br><span class="line">               processedBeans.add(ppName);</span><br><span class="line">               reiterate = <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;<span class="comment">//排序，根据类名大小写进行排序</span></span><br><span class="line">         sortPostProcessors(currentRegistryProcessors, beanFactory);</span><br><span class="line">         registryProcessors.addAll(currentRegistryProcessors);</span><br><span class="line">         invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());</span><br><span class="line">         currentRegistryProcessors.clear(); <span class="comment">//防止重复执行</span></span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 接下来，再来执行postProcessBeanFactory的回调， Now, invoke the postProcessBeanFactory callback of all processors handled so far.</span></span><br><span class="line">      invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);</span><br><span class="line">      invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// Invoke factory processors registered with the context instance.</span></span><br><span class="line">      invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="comment">//以前在执行 BeanDefinitionRegistryPostProcessor ,以后来执行 BeanFactoryPostProcessor</span></span><br><span class="line">   <span class="comment">// Do not initialize FactoryBeans here: We need to leave all regular beans</span></span><br><span class="line">   <span class="comment">// uninitialized to let the bean factory post-processors apply to them!</span></span><br><span class="line">   String[] postProcessorNames =</span><br><span class="line">         beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, <span class="keyword">true</span>, <span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,</span></span><br><span class="line">   <span class="comment">// Ordered, and the rest.</span></span><br><span class="line">   List&lt;BeanFactoryPostProcessor&gt; priorityOrderedPostProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">   List&lt;String&gt; orderedPostProcessorNames = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">   List&lt;String&gt; nonOrderedPostProcessorNames = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">   <span class="keyword">for</span> (String ppName : postProcessorNames) &#123;</span><br><span class="line">      <span class="keyword">if</span> (processedBeans.contains(ppName)) &#123;</span><br><span class="line">         <span class="comment">// skip - already processed in first phase above</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) &#123;</span><br><span class="line">         priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (beanFactory.isTypeMatch(ppName, Ordered.class)) &#123;</span><br><span class="line">         orderedPostProcessorNames.add(ppName);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         nonOrderedPostProcessorNames.add(ppName);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 首先执行所有实现了 PriorityOrdered 的 BeanFactoryPostProcessor；First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.</span></span><br><span class="line">   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);</span><br><span class="line">   invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 接下来执行，实现了 Ordered 接口的 BeanFactoryPostProcessor  Next, invoke the BeanFactoryPostProcessors that implement Ordered.</span></span><br><span class="line">   List&lt;BeanFactoryPostProcessor&gt; orderedPostProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;(orderedPostProcessorNames.size());</span><br><span class="line">   <span class="keyword">for</span> (String postProcessorName : orderedPostProcessorNames) &#123;</span><br><span class="line">      orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));</span><br><span class="line">   &#125;</span><br><span class="line">   sortPostProcessors(orderedPostProcessors, beanFactory);</span><br><span class="line">   invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 最后执行没有任何优先级和排序接口的 BeanFactoryPostProcessor Finally, invoke all other BeanFactoryPostProcessors.</span></span><br><span class="line">   List&lt;BeanFactoryPostProcessor&gt; nonOrderedPostProcessors = <span class="keyword">new</span> ArrayList&lt;&gt;(nonOrderedPostProcessorNames.size());</span><br><span class="line">   <span class="keyword">for</span> (String postProcessorName : nonOrderedPostProcessorNames) &#123;</span><br><span class="line">      nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));</span><br><span class="line">   &#125;</span><br><span class="line">   invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); <span class="comment">//执行所有的 BeanFactoryPostProcessor</span></span><br><span class="line"></span><br><span class="line">   <span class="comment">// Clear cached merged bean definitions since the post-processors might have</span></span><br><span class="line">   <span class="comment">// modified the original metadata, e.g. replacing placeholders in values...</span></span><br><span class="line">   beanFactory.clearMetadataCache();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>后面就是走前面讲过的getBean,无参构造创建对象的流程</p>
<blockquote>
<p>Spring中所有组件的获取都是通过getBean()，容器中有就拿，没有就创建。</p>
</blockquote>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928203211130.png" />

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928195709384.png" />

<p>下面那个是Spring默认提供的后置处理器，我们后面再讲。</p>
<h6 id="PriorityOrdered或Ordered实现排序"><a href="#PriorityOrdered或Ordered实现排序" class="headerlink" title="PriorityOrdered或Ordered实现排序"></a>PriorityOrdered或Ordered实现排序</h6><p>那么这些后置处理器的顺序Spring是如何排序的呢？我们又该怎样自定义BeanPostProcessor的顺序？我们可以通过实现PriorityOrdered或Ordered这两接口来自定义BeanPostProcessor的执行顺序。</p>
<p>PriorityOrdered是个空类，啥也没有</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">PriorityOrdered</span> <span class="keyword">extends</span> <span class="title">Ordered</span> </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们只能看他的父类</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Ordered</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Useful constant for the highest precedence value.</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@see</span> java.lang.Integer#MIN_VALUE</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="keyword">int</span> HIGHEST_PRECEDENCE = Integer.MIN_VALUE;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Useful constant for the lowest precedence value.</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@see</span> java.lang.Integer#MAX_VALUE</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="keyword">int</span> LOWEST_PRECEDENCE = Integer.MAX_VALUE;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Get the order value of this object.</span></span><br><span class="line"><span class="comment">    * &lt;p&gt;Higher values are interpreted as lower priority. As a consequence,</span></span><br><span class="line"><span class="comment">    * the object with the lowest value has the highest priority (somewhat</span></span><br><span class="line"><span class="comment">    * analogous to Servlet &#123;<span class="doctag">@code</span> load-on-startup&#125; values).</span></span><br><span class="line"><span class="comment">    * &lt;p&gt;Same order values will result in arbitrary sort positions for the</span></span><br><span class="line"><span class="comment">    * affected objects.java</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@return</span> the order value</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@see</span> #HIGHEST_PRECEDENCE</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@see</span> #LOWEST_PRECEDENCE</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="function"><span class="keyword">int</span> <span class="title">getOrder</span><span class="params">()</span></span>; <span class="comment">//根据注释我们可以知道返回的int值越小优先级越高，反之越低</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol>
<li>从上面的源码中我们可以看到PriorityOrdered的代码在Ordered代码前面，获取完PriorityOrdered的BeanDefinitionRegistryPostProcessor就直接invokeBeanDefinitionRegistryPostProcessors执行了，所以如果有多个组件，这些组件有些实现了PriorityOrdered ，有些实现了Ordered。实现了PriorityOrdered 的组件执行顺序永远大于实现了Ordered的组件。</li>
<li>即使同时实现了 PriorityOrdered 和Ordered，也是以 PriorityOrdered为准。</li>
</ol>
<h4 id="执行postProcessBeanDefinitionRegistry方法"><a href="#执行postProcessBeanDefinitionRegistry方法" class="headerlink" title="执行postProcessBeanDefinitionRegistry方法"></a>执行postProcessBeanDefinitionRegistry方法</h4><h5 id="Debug调用栈-1"><a href="#Debug调用栈-1" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h5><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928203957687.png"/>

<p>从PostProcessorRegistrationDelegate 142行开始走不同的调用，代码在上面有注释</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928204229225.png" />

<h5 id="PostProcessorRegistrationDelegate-invokeBeanDefinitionRegistryPostProcessors"><a href="#PostProcessorRegistrationDelegate-invokeBeanDefinitionRegistryPostProcessors" class="headerlink" title="PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors()"></a>PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">invokeBeanDefinitionRegistryPostProcessors</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">      Collection&lt;? extends BeanDefinitionRegistryPostProcessor&gt; postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">for</span> (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) &#123;</span><br><span class="line">      StartupStep postProcessBeanDefRegistry = applicationStartup.start(<span class="string">&quot;spring.context.beandef-registry.post-process&quot;</span>)</span><br><span class="line">            .tag(<span class="string">&quot;postProcessor&quot;</span>, postProcessor::toString);</span><br><span class="line">      postProcessor.postProcessBeanDefinitionRegistry(registry);<span class="comment">//在这里就多态调用我们自定义的方法，也可以说是模板模式</span></span><br><span class="line">      postProcessBeanDefRegistry.end();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h4 id="执行postProcessBeanFactory"><a href="#执行postProcessBeanFactory" class="headerlink" title="执行postProcessBeanFactory"></a>执行postProcessBeanFactory</h4><h5 id="Debug调用栈-2"><a href="#Debug调用栈-2" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h5><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928204806052.png" />



<h5 id="PostProcessorRegistrationDelegate-invokeBeanFactoryPostProcessors-1"><a href="#PostProcessorRegistrationDelegate-invokeBeanFactoryPostProcessors-1" class="headerlink" title="PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors()"></a>PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">invokeBeanFactoryPostProcessors</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">      Collection&lt;? extends BeanFactoryPostProcessor&gt; postProcessors, ConfigurableListableBeanFactory beanFactory)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">for</span> (BeanFactoryPostProcessor postProcessor : postProcessors) &#123;</span><br><span class="line">      StartupStep postProcessBeanFactory = beanFactory.getApplicationStartup().start(<span class="string">&quot;spring.context.bean-factory.post-process&quot;</span>)</span><br><span class="line">            .tag(<span class="string">&quot;postProcessor&quot;</span>, postProcessor::toString);</span><br><span class="line">      postProcessor.postProcessBeanFactory(beanFactory); <span class="comment">//一样的多态调用我们自定义的方法</span></span><br><span class="line">      postProcessBeanFactory.end();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="BeanFactoryPostProcessor"><a href="#BeanFactoryPostProcessor" class="headerlink" title="BeanFactoryPostProcessor"></a>BeanFactoryPostProcessor</h3><h4 id="执行无参构造-1"><a href="#执行无参构造-1" class="headerlink" title="执行无参构造"></a>执行无参构造</h4><h5 id="Debug调用栈-3"><a href="#Debug调用栈-3" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h5><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928210240702.png" />



<h4 id="执行postProcessBeanFactory-1"><a href="#执行postProcessBeanFactory-1" class="headerlink" title="执行postProcessBeanFactory"></a>执行postProcessBeanFactory</h4><h5 id="Debug调用栈-4"><a href="#Debug调用栈-4" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h5><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928210858103.png">

<p>代码注释也是上面那个，BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor执行逻辑基本一样</p>
<blockquote>
<p>上面两个都是BeanFactoryPostProcessor，也就是增强Bean工厂的</p>
</blockquote>
<h3 id="Spring内部的工厂增强了什么？-简单说明"><a href="#Spring内部的工厂增强了什么？-简单说明" class="headerlink" title="Spring内部的工厂增强了什么？-简单说明"></a>Spring内部的工厂增强了什么？-简单说明</h3><p>我们用注解版启动一下</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AnnotationMainTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">      ApplicationContext applicationContext = <span class="keyword">new</span> AnnotationConfigApplicationContext(MainConfig.class);</span><br><span class="line">      Person bean = applicationContext.getBean(Person.class);</span><br><span class="line">      ApplicationContext context = bean.getContext();</span><br><span class="line">      System.out.println(context == applicationContext);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@ComponentScan(&quot;cn.imlql.spring&quot;)</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MainConfig</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MainConfig...创建了....&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928211847405.png" />

<p>从这一步进来</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928212026255.png"  />





<h4 id="PostProcessorRegistrationDelegate-invokeBeanDefinitionRegistryPostProcessors-1"><a href="#PostProcessorRegistrationDelegate-invokeBeanDefinitionRegistryPostProcessors-1" class="headerlink" title="PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors()"></a>PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors()</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928212134359.png"  />

<p>F7进入</p>
<h4 id="ConfigurationClassPostProcessor-postProcessBeanDefinitionRegistry"><a href="#ConfigurationClassPostProcessor-postProcessBeanDefinitionRegistry" class="headerlink" title="ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry()"></a>ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry()</h4><p>ConfigurationClassPostProcessor配置类的后置处理</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928212332382.png"  />



<h4 id="ConfigurationClassPostProcessor-processConfigBeanDefinitions"><a href="#ConfigurationClassPostProcessor-processConfigBeanDefinitions" class="headerlink" title="ConfigurationClassPostProcessor#processConfigBeanDefinitions()"></a>ConfigurationClassPostProcessor#processConfigBeanDefinitions()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">processConfigBeanDefinitions</span><span class="params">(BeanDefinitionRegistry registry)</span> </span>&#123;</span><br><span class="line">   List&lt;BeanDefinitionHolder&gt; configCandidates = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">   String[] candidateNames = registry.getBeanDefinitionNames();</span><br><span class="line"></span><br><span class="line">   <span class="keyword">for</span> (String beanName : candidateNames) &#123;</span><br><span class="line">      BeanDefinition beanDef = registry.getBeanDefinition(beanName);</span><br><span class="line">      <span class="keyword">if</span> (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != <span class="keyword">null</span>) &#123;</span><br><span class="line">         <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">&quot;Bean definition has already been processed as a configuration class: &quot;</span> + beanDef);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, <span class="keyword">this</span>.metadataReaderFactory)) &#123;</span><br><span class="line">         configCandidates.add(<span class="keyword">new</span> BeanDefinitionHolder(beanDef, beanName)); <span class="comment">//将配置类加到候选集合里面，等待处理</span></span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Return immediately if no @Configuration classes were found</span></span><br><span class="line">   <span class="keyword">if</span> (configCandidates.isEmpty()) &#123;</span><br><span class="line">      <span class="keyword">return</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 对所有的配置类进行排序，Sort by previously determined @Order value, if applicable</span></span><br><span class="line">   configCandidates.sort((bd1, bd2) -&gt; &#123;</span><br><span class="line">      <span class="keyword">int</span> i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());</span><br><span class="line">      <span class="keyword">int</span> i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());</span><br><span class="line">      <span class="keyword">return</span> Integer.compare(i1, i2);</span><br><span class="line">   &#125;);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 单实例注册中心</span></span><br><span class="line">   SingletonBeanRegistry sbr = <span class="keyword">null</span>;</span><br><span class="line">   <span class="keyword">if</span> (registry <span class="keyword">instanceof</span> SingletonBeanRegistry) &#123;</span><br><span class="line">      sbr = (SingletonBeanRegistry) registry;</span><br><span class="line">      <span class="keyword">if</span> (!<span class="keyword">this</span>.localBeanNameGeneratorSet) &#123;</span><br><span class="line">         BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(</span><br><span class="line">               AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); <span class="comment">//getBean--getSingleton，获取创建一个internalConfigurationBeanNameGenerator来用来生成配置类的名字</span></span><br><span class="line">         <span class="keyword">if</span> (generator != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">this</span>.componentScanBeanNameGenerator = generator;</span><br><span class="line">            <span class="keyword">this</span>.importBeanNameGenerator = generator;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.environment == <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">this</span>.environment = <span class="keyword">new</span> StandardEnvironment();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Parse each @Configuration class  由ConfigurationClassParser解析每一个配置类</span></span><br><span class="line">   ConfigurationClassParser parser = <span class="keyword">new</span> ConfigurationClassParser(</span><br><span class="line">         <span class="keyword">this</span>.metadataReaderFactory, <span class="keyword">this</span>.problemReporter, <span class="keyword">this</span>.environment,</span><br><span class="line">         <span class="keyword">this</span>.resourceLoader, <span class="keyword">this</span>.componentScanBeanNameGenerator, registry);</span><br><span class="line"></span><br><span class="line">   Set&lt;BeanDefinitionHolder&gt; candidates = <span class="keyword">new</span> LinkedHashSet&lt;&gt;(configCandidates);</span><br><span class="line">   Set&lt;ConfigurationClass&gt; alreadyParsed = <span class="keyword">new</span> HashSet&lt;&gt;(configCandidates.size());</span><br><span class="line">   <span class="keyword">do</span> &#123;</span><br><span class="line">      StartupStep processConfig = <span class="keyword">this</span>.applicationStartup.start(<span class="string">&quot;spring.context.config-classes.parse&quot;</span>);</span><br><span class="line">      parser.parse(candidates);  </span><br><span class="line">      parser.validate();</span><br><span class="line"></span><br><span class="line">      Set&lt;ConfigurationClass&gt; configClasses = <span class="keyword">new</span> LinkedHashSet&lt;&gt;(parser.getConfigurationClasses());</span><br><span class="line">      configClasses.removeAll(alreadyParsed);</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Read the model and create bean definitions based on its content</span></span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">this</span>.reader == <span class="keyword">null</span>) &#123;</span><br><span class="line">         <span class="keyword">this</span>.reader = <span class="keyword">new</span> ConfigurationClassBeanDefinitionReader(</span><br><span class="line">               registry, <span class="keyword">this</span>.sourceExtractor, <span class="keyword">this</span>.resourceLoader, <span class="keyword">this</span>.environment,</span><br><span class="line">               <span class="keyword">this</span>.importBeanNameGenerator, parser.getImportRegistry());</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">this</span>.reader.loadBeanDefinitions(configClasses);</span><br><span class="line">      alreadyParsed.addAll(configClasses);</span><br><span class="line">      processConfig.tag(<span class="string">&quot;classCount&quot;</span>, () -&gt; String.valueOf(configClasses.size())).end();</span><br><span class="line"></span><br><span class="line">      candidates.clear();</span><br><span class="line">      <span class="keyword">if</span> (registry.getBeanDefinitionCount() &gt; candidateNames.length) &#123;</span><br><span class="line">         String[] newCandidateNames = registry.getBeanDefinitionNames();</span><br><span class="line">         Set&lt;String&gt; oldCandidateNames = <span class="keyword">new</span> HashSet&lt;&gt;(Arrays.asList(candidateNames));</span><br><span class="line">         Set&lt;String&gt; alreadyParsedClasses = <span class="keyword">new</span> HashSet&lt;&gt;();</span><br><span class="line">         <span class="keyword">for</span> (ConfigurationClass configurationClass : alreadyParsed) &#123;</span><br><span class="line">            alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">for</span> (String candidateName : newCandidateNames) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!oldCandidateNames.contains(candidateName)) &#123;</span><br><span class="line">               BeanDefinition bd = registry.getBeanDefinition(candidateName);</span><br><span class="line">               <span class="keyword">if</span> (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, <span class="keyword">this</span>.metadataReaderFactory) &amp;&amp;</span><br><span class="line">                     !alreadyParsedClasses.contains(bd.getBeanClassName())) &#123;</span><br><span class="line">                  candidates.add(<span class="keyword">new</span> BeanDefinitionHolder(bd, candidateName));</span><br><span class="line">               &#125;</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">         candidateNames = newCandidateNames;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">while</span> (!candidates.isEmpty());</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes</span></span><br><span class="line">   <span class="keyword">if</span> (sbr != <span class="keyword">null</span> &amp;&amp; !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) &#123;</span><br><span class="line">      sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.metadataReaderFactory <span class="keyword">instanceof</span> CachingMetadataReaderFactory) &#123;</span><br><span class="line">      <span class="comment">// Clear cache in externally provided MetadataReaderFactory; this is a no-op</span></span><br><span class="line">      <span class="comment">// for a shared cache since it&#x27;ll be cleared by the ApplicationContext.</span></span><br><span class="line">      ((CachingMetadataReaderFactory) <span class="keyword">this</span>.metadataReaderFactory).clearCache();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这几个怎么来的我们后面说</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_02/image-20210928212543963.png"  />



<p>最终上面的调用栈会<code>parser.parse(candidates);</code>  一直调到下面的<code>ConfigurationClassParser#processConfigurationClass()</code>，这里也是简单过一下，后面还会再讲。</p>
<h4 id="ConfigurationClassParser-processConfigurationClass"><a href="#ConfigurationClassParser-processConfigurationClass" class="headerlink" title="ConfigurationClassParser#processConfigurationClass()"></a>ConfigurationClassParser#processConfigurationClass()</h4><p>配置类解析的核心方法</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">processConfigurationClass</span><span class="params">(ConfigurationClass configClass, Predicate&lt;String&gt; filter)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (<span class="keyword">this</span>.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) &#123;</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//Spring底层大量使用缓存来保证框架速度</span></span><br><span class="line">	ConfigurationClass existingClass = <span class="keyword">this</span>.configurationClasses.get(configClass);</span><br><span class="line">	<span class="keyword">if</span> (existingClass != <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">if</span> (configClass.isImported()) &#123;</span><br><span class="line">			<span class="keyword">if</span> (existingClass.isImported()) &#123;</span><br><span class="line">				existingClass.mergeImportedBy(configClass);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="comment">// Otherwise ignore new imported config class; existing non-imported class overrides it.</span></span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="comment">// Explicit bean definition found, probably replacing an import.</span></span><br><span class="line">			<span class="comment">// Let&#x27;s remove the old one and go with the new one.</span></span><br><span class="line">			<span class="keyword">this</span>.configurationClasses.remove(configClass);</span><br><span class="line">			<span class="keyword">this</span>.knownSuperclasses.values().removeIf(configClass::equals);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Recursively process the configuration class and its superclass hierarchy.</span></span><br><span class="line">	SourceClass sourceClass = asSourceClass(configClass, filter);</span><br><span class="line">	<span class="keyword">do</span> &#123; <span class="comment">//解析配置类里面的所有注解，</span></span><br><span class="line">		sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">while</span> (sourceClass != <span class="keyword">null</span>);</span><br><span class="line">	<span class="comment">//只要这个配置类解析过，就放在已经解析好的集合中防止重复解析</span></span><br><span class="line">	<span class="keyword">this</span>.configurationClasses.put(configClass, configClass);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Apply processing and build a complete &#123;<span class="doctag">@link</span> ConfigurationClass&#125; by reading the</span></span><br><span class="line"><span class="comment"> * annotations, members and methods from the source class. This method can be called</span></span><br><span class="line"><span class="comment"> * multiple times as relevant sources are discovered.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> configClass the configuration class being build</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> sourceClass a source class</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the superclass, or &#123;<span class="doctag">@code</span> null&#125; if none found or previously processed</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> SourceClass <span class="title">doProcessConfigurationClass</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">		ConfigurationClass configClass, SourceClass sourceClass, Predicate&lt;String&gt; filter)</span></span></span><br><span class="line"><span class="function">		<span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (configClass.getMetadata().isAnnotated(Component.class.getName())) &#123;</span><br><span class="line">		<span class="comment">// Recursively process any member (nested) classes first</span></span><br><span class="line">		processMemberClasses(configClass, sourceClass, filter);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Process any @PropertySource annotations</span></span><br><span class="line">	<span class="keyword">for</span> (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(</span><br><span class="line">			sourceClass.getMetadata(), PropertySources.class,</span><br><span class="line">			org.springframework.context.annotation.PropertySource.class)) &#123;</span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">this</span>.environment <span class="keyword">instanceof</span> ConfigurableEnvironment) &#123;</span><br><span class="line">			processPropertySource(propertySource);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			logger.info(<span class="string">&quot;Ignoring @PropertySource annotation on [&quot;</span> + sourceClass.getMetadata().getClassName() +</span><br><span class="line">					<span class="string">&quot;]. Reason: Environment must implement ConfigurableEnvironment&quot;</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Process any @ComponentScan annotations</span></span><br><span class="line">	Set&lt;AnnotationAttributes&gt; componentScans = AnnotationConfigUtils.attributesForRepeatable(</span><br><span class="line">			sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);</span><br><span class="line">	<span class="keyword">if</span> (!componentScans.isEmpty() &amp;&amp;</span><br><span class="line">			!<span class="keyword">this</span>.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) &#123;</span><br><span class="line">		<span class="keyword">for</span> (AnnotationAttributes componentScan : componentScans) &#123;</span><br><span class="line">			<span class="comment">//使用Scanner把ComponentScan指定的包下的所有组件都扫描进来 The config class is annotated with @ComponentScan -&gt; perform the scan immediately</span></span><br><span class="line">			Set&lt;BeanDefinitionHolder&gt; scannedBeanDefinitions =</span><br><span class="line">					<span class="keyword">this</span>.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());</span><br><span class="line">			<span class="comment">// Check the set of scanned definitions for any further config classes and parse recursively if needed</span></span><br><span class="line">			<span class="keyword">for</span> (BeanDefinitionHolder holder : scannedBeanDefinitions) &#123;</span><br><span class="line">				BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();</span><br><span class="line">				<span class="keyword">if</span> (bdCand == <span class="keyword">null</span>) &#123;</span><br><span class="line">					bdCand = holder.getBeanDefinition();</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">if</span> (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, <span class="keyword">this</span>.metadataReaderFactory)) &#123;</span><br><span class="line">					parse(bdCand.getBeanClassName(), holder.getBeanName());</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//处理@Import注解的地方【AOP就是利用这个地方导入一个后置处理器的】 Process any @Import annotations</span></span><br><span class="line">	processImports(configClass, sourceClass, getImports(sourceClass), filter, <span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//处理@ImportResource  Process any @ImportResource annotations</span></span><br><span class="line">	AnnotationAttributes importResource =</span><br><span class="line">			AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);</span><br><span class="line">	<span class="keyword">if</span> (importResource != <span class="keyword">null</span>) &#123;</span><br><span class="line">		String[] resources = importResource.getStringArray(<span class="string">&quot;locations&quot;</span>);</span><br><span class="line">		Class&lt;? extends BeanDefinitionReader&gt; readerClass = importResource.getClass(<span class="string">&quot;reader&quot;</span>);</span><br><span class="line">		<span class="keyword">for</span> (String resource : resources) &#123;</span><br><span class="line">			String resolvedResource = <span class="keyword">this</span>.environment.resolveRequiredPlaceholders(resource);</span><br><span class="line">			configClass.addImportedResource(resolvedResource, readerClass);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//处理@Bean Process individual @Bean methods</span></span><br><span class="line">	Set&lt;MethodMetadata&gt; beanMethods = retrieveBeanMethodMetadata(sourceClass);</span><br><span class="line">	<span class="keyword">for</span> (MethodMetadata methodMetadata : beanMethods) &#123;</span><br><span class="line">		configClass.addBeanMethod(<span class="keyword">new</span> BeanMethod(methodMetadata, configClass));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Process default methods on interfaces</span></span><br><span class="line">	processInterfaces(configClass, sourceClass);</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Process superclass, if any</span></span><br><span class="line">	<span class="keyword">if</span> (sourceClass.getMetadata().hasSuperClass()) &#123;</span><br><span class="line">		String superclass = sourceClass.getMetadata().getSuperClassName();</span><br><span class="line">		<span class="keyword">if</span> (superclass != <span class="keyword">null</span> &amp;&amp; !superclass.startsWith(<span class="string">&quot;java&quot;</span>) &amp;&amp;</span><br><span class="line">				!<span class="keyword">this</span>.knownSuperclasses.containsKey(superclass)) &#123;</span><br><span class="line">			<span class="keyword">this</span>.knownSuperclasses.put(superclass, configClass);</span><br><span class="line">			<span class="comment">// Superclass found, return its annotation metadata and recurse</span></span><br><span class="line">			<span class="keyword">return</span> sourceClass.getSuperClass();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// No superclass -&gt; processing is complete</span></span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<blockquote>
<p>至此，后置工厂处理器结束，后面讲后置处理器</p>
</blockquote>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">youthlql</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://imlql.cn/post/41fb8d9e.html">https://imlql.cn/post/41fb8d9e.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://imlql.cn" target="_blank">风祈的时光录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring%E6%BA%90%E7%A0%81/">Spring源码</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/66c146e7.html"><img class="prev-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Spring源码系列-第3章-后置处理器和Bean生命周期</div></div></a></div><div class="next-post pull-right"><a href="/post/599156d.html"><img class="next-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Spring源码系列-第1章-Spring源码纵览</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/post/49f419ae.html" title="Spring源码系列-第4章-Bean初始化流程"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-27</div><div class="title">Spring源码系列-第4章-Bean初始化流程</div></div></a></div><div><a href="/post/fb3552e0.html" title="Spring源码系列-第7章-AOP的执行流程原理和监听器原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-04-17</div><div class="title">Spring源码系列-第7章-AOP的执行流程原理和监听器原理</div></div></a></div><div><a href="/post/c8dd1418.html" title="Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-20</div><div class="title">Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理</div></div></a></div><div><a href="/post/6f2cef28.html" title="Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-21</div><div class="title">Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理</div></div></a></div><div><a href="/post/4dfb096b.html" title="Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-05</div><div class="title">Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理</div></div></a></div><div><a href="/post/e3da4d66.html" title="Spring源码系列-第12章-SpringBoot源码-自动配置原理和内嵌Tomcat启动原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-06</div><div class="title">Spring源码系列-第12章-SpringBoot源码-自动配置原理和内嵌Tomcat启动原理</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC2%E7%AB%A0-%E5%90%8E%E7%BD%AE%E5%B7%A5%E5%8E%82%E5%A4%84%E7%90%86%E5%99%A8%E5%92%8CBean%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-text">第2章-后置工厂处理器和Bean生命周期</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFBeanPostProcessor%EF%BC%9F"><span class="toc-text">什么是BeanPostProcessor？</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#BeanFactoryPostProcessor%E7%9A%84%E6%8E%A5%E5%8F%A3%E5%85%B3%E7%B3%BB"><span class="toc-text">BeanFactoryPostProcessor的接口关系</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#BeanPostProcessor%E6%8E%A5%E5%8F%A3%E5%85%B3%E7%B3%BB"><span class="toc-text">BeanPostProcessor接口关系</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFInitializingBean%EF%BC%9F"><span class="toc-text">什么是InitializingBean？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%8B%E8%AF%95%E7%B1%BB"><span class="toc-text">测试类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#MyBeanPostProcessor"><span class="toc-text">MyBeanPostProcessor</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MyInstantiationAwareBeanPostProcessor"><span class="toc-text">MyInstantiationAwareBeanPostProcessor</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MyMergedBeanDefinitionPostProcessor"><span class="toc-text">MyMergedBeanDefinitionPostProcessor</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MySmartInstantiationAwareBeanPostProcessor"><span class="toc-text">MySmartInstantiationAwareBeanPostProcessor</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MyInitializingBean"><span class="toc-text">MyInitializingBean</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MyBeanFactoryPostProcessor"><span class="toc-text">MyBeanFactoryPostProcessor</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MyBeanDefinitionRegistryPostProcessor"><span class="toc-text">MyBeanDefinitionRegistryPostProcessor</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Cat"><span class="toc-text">Cat</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#beans2-xml"><span class="toc-text">beans2.xml</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MainTest"><span class="toc-text">MainTest</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%8E%E7%BD%AE%E5%B7%A5%E5%8E%82%E5%A4%84%E7%90%86%E5%99%A8%E5%A6%82%E4%BD%95%E5%8F%82%E4%B8%8E%E7%9A%84Bean%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-text">后置工厂处理器如何参与的Bean生命周期</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E5%9B%BE-Bean%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E4%B8%8E%E5%90%8E%E7%BD%AE%E5%B7%A5%E5%8E%82%E5%A4%84%E7%90%86%E5%99%A8"><span class="toc-text">流程图-Bean生命周期与后置工厂处理器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#BeanDefinitionRegistryPostProcessor"><span class="toc-text">BeanDefinitionRegistryPostProcessor</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%89%A7%E8%A1%8C%E6%97%A0%E5%8F%82%E6%9E%84%E9%80%A0"><span class="toc-text">执行无参构造</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractApplicationContext-refresh"><span class="toc-text">AbstractApplicationContext#refresh()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#PostProcessorRegistrationDelegate-invokeBeanFactoryPostProcessors"><span class="toc-text">PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors()</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#PriorityOrdered%E6%88%96Ordered%E5%AE%9E%E7%8E%B0%E6%8E%92%E5%BA%8F"><span class="toc-text">PriorityOrdered或Ordered实现排序</span></a></li></ol></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%89%A7%E8%A1%8CpostProcessBeanDefinitionRegistry%E6%96%B9%E6%B3%95"><span class="toc-text">执行postProcessBeanDefinitionRegistry方法</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-1"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#PostProcessorRegistrationDelegate-invokeBeanDefinitionRegistryPostProcessors"><span class="toc-text">PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors()</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%89%A7%E8%A1%8CpostProcessBeanFactory"><span class="toc-text">执行postProcessBeanFactory</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-2"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#PostProcessorRegistrationDelegate-invokeBeanFactoryPostProcessors-1"><span class="toc-text">PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors()</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#BeanFactoryPostProcessor"><span class="toc-text">BeanFactoryPostProcessor</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%89%A7%E8%A1%8C%E6%97%A0%E5%8F%82%E6%9E%84%E9%80%A0-1"><span class="toc-text">执行无参构造</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-3"><span class="toc-text">Debug调用栈</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%89%A7%E8%A1%8CpostProcessBeanFactory-1"><span class="toc-text">执行postProcessBeanFactory</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-4"><span class="toc-text">Debug调用栈</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Spring%E5%86%85%E9%83%A8%E7%9A%84%E5%B7%A5%E5%8E%82%E5%A2%9E%E5%BC%BA%E4%BA%86%E4%BB%80%E4%B9%88%EF%BC%9F-%E7%AE%80%E5%8D%95%E8%AF%B4%E6%98%8E"><span class="toc-text">Spring内部的工厂增强了什么？-简单说明</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#PostProcessorRegistrationDelegate-invokeBeanDefinitionRegistryPostProcessors-1"><span class="toc-text">PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ConfigurationClassPostProcessor-postProcessBeanDefinitionRegistry"><span class="toc-text">ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ConfigurationClassPostProcessor-processConfigBeanDefinitions"><span class="toc-text">ConfigurationClassPostProcessor#processConfigBeanDefinitions()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ConfigurationClassParser-processConfigurationClass"><span class="toc-text">ConfigurationClassParser#processConfigurationClass()</span></a></li></ol></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By youthlql</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" target="_blank" rel="noopener" class="one-pan-link-mark"><img style="position:relative;top:-3px; " src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/upyun/logo.png" align="absmiddle" width="60px" height="30px"></a><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn"><img class="icp-icon" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/icp.png"><span>鄂ICP备19028890号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://npm.elemecdn.com/instant.page/instantpage.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script></div></body></html>